package com.blobfish.fiction.common.util;

import cn.hutool.core.util.StrUtil;
import com.blobfish.fiction.common.base.model.QmResult;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;

import java.util.Enumeration;

/**
 * 验证消息生成器
 * @author huangbo
 */
public class ValiMessageUtil {
    private static final Log log = Log.getLog(ValiMessageUtil.class);

    /**
     * 生成验证异常对象
     * @param controller
     * @return
     */
    public static QmResult<? extends Model> getMessage(Controller controller) {
        QmResult qmResult = new QmResult();
        qmResult.setCode(500);
        Enumeration<String> keysItr = controller.getAttrNames();
        StringBuffer errMsg = new StringBuffer();
        while (keysItr.hasMoreElements()) {
            String errKey = keysItr.nextElement();
            String errMsgItem = PropKit.use("message.txt").get(errKey);
            if (StrUtil.isBlank(errMsgItem)) {
                log.error(StrUtil.format("can not find key:[{}] on message.txt!", errKey));
                continue;
            }
            errMsg.append(errMsgItem).append(";");
        }
        qmResult.setMsg(errMsg.toString());
        return qmResult;
    }
}
